[[...path]].page.tsx 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672
  1. import type { ReactNode } from 'react';
  2. import React, { useEffect } from 'react';
  3. import EventEmitter from 'events';
  4. import { isIPageInfoForEntity, isPopulated } from '@growi/core';
  5. import type {
  6. GroupType,
  7. IDataWithMeta, IPageInfoForEntity, IPagePopulatedToShowRevision,
  8. } from '@growi/core';
  9. import {
  10. isClient, pagePathUtils, pathUtils,
  11. } from '@growi/core/dist/utils';
  12. import ExtensibleCustomError from 'extensible-custom-error';
  13. import type {
  14. GetServerSideProps, GetServerSidePropsContext,
  15. } from 'next';
  16. import { serverSideTranslations } from 'next-i18next/serverSideTranslations';
  17. import dynamic from 'next/dynamic';
  18. import Head from 'next/head';
  19. import { useRouter } from 'next/router';
  20. import superjson from 'superjson';
  21. import { useEditorModeClassName } from '~/client/services/layout';
  22. import { PageView } from '~/components/Page/PageView';
  23. import { DrawioViewerScript } from '~/components/Script/DrawioViewerScript';
  24. import { SupportedAction, type SupportedActionType } from '~/interfaces/activity';
  25. import type { CrowiRequest } from '~/interfaces/crowi-request';
  26. import type { IPageGrantData } from '~/interfaces/page';
  27. import type { RendererConfig } from '~/interfaces/services/renderer';
  28. import type { PageModel, PageDocument } from '~/server/models/page';
  29. import type { PageRedirectModel } from '~/server/models/page-redirect';
  30. import {
  31. useCurrentUser,
  32. useIsForbidden, useIsSharedUser,
  33. useIsEnabledStaleNotification, useIsIdenticalPath,
  34. useIsSearchServiceConfigured, useIsSearchServiceReachable, useDisableLinkSharing,
  35. useDefaultIndentSize, useIsIndentSizeForced,
  36. useIsAclEnabled, useIsSearchPage, useIsEnabledAttachTitleHeader,
  37. useCsrfToken, useIsSearchScopeChildrenAsDefault, useIsEnabledMarp, useCurrentPathname,
  38. useIsSlackConfigured, useRendererConfig, useGrowiCloudUri,
  39. useIsAllReplyShown, useIsContainerFluid, useIsNotCreatable,
  40. useIsUploadAllFileAllowed, useIsUploadEnabled,
  41. } from '~/stores/context';
  42. import { useEditingMarkdown } from '~/stores/editor';
  43. import {
  44. useSWRxCurrentPage, useSWRMUTxCurrentPage, useSWRxIsGrantNormalized, useCurrentPageId,
  45. useIsNotFound, useIsLatestRevision, useTemplateTagData, useTemplateBodyData,
  46. } from '~/stores/page';
  47. import { useRedirectFrom } from '~/stores/page-redirect';
  48. import { useRemoteRevisionId } from '~/stores/remote-latest-page';
  49. import { useSelectedGrant } from '~/stores/ui';
  50. import { useSetupGlobalSocket, useSetupGlobalSocketForPage } from '~/stores/websocket';
  51. import loggerFactory from '~/utils/logger';
  52. import { BasicLayout } from '../components/Layout/BasicLayout';
  53. import GrowiContextualSubNavigationSubstance from '../components/Navbar/GrowiContextualSubNavigation';
  54. import { DisplaySwitcher } from '../components/Page/DisplaySwitcher';
  55. import type { NextPageWithLayout } from './_app.page';
  56. import type { CommonProps } from './utils/commons';
  57. import {
  58. getNextI18NextConfig, getServerSideCommonProps, generateCustomTitleForPage, useInitSidebarConfig, skipSSR, addActivity,
  59. } from './utils/commons';
  60. declare global {
  61. // eslint-disable-next-line vars-on-top, no-var
  62. var globalEmitter: EventEmitter;
  63. }
  64. const GrowiPluginsActivator = dynamic(() => import('~/features/growi-plugin/client/components').then(mod => mod.GrowiPluginsActivator), { ssr: false });
  65. const DescendantsPageListModal = dynamic(() => import('../components/DescendantsPageListModal').then(mod => mod.DescendantsPageListModal), { ssr: false });
  66. const UnsavedAlertDialog = dynamic(() => import('../components/UnsavedAlertDialog'), { ssr: false });
  67. const DrawioModal = dynamic(() => import('../components/PageEditor/DrawioModal').then(mod => mod.DrawioModal), { ssr: false });
  68. const HandsontableModal = dynamic(() => import('../components/PageEditor/HandsontableModal').then(mod => mod.HandsontableModal), { ssr: false });
  69. const TemplateModal = dynamic(() => import('../components/TemplateModal').then(mod => mod.TemplateModal), { ssr: false });
  70. const LinkEditModal = dynamic(() => import('../components/PageEditor/LinkEditModal').then(mod => mod.LinkEditModal), { ssr: false });
  71. const PageStatusAlert = dynamic(() => import('../components/PageStatusAlert').then(mod => mod.PageStatusAlert), { ssr: false });
  72. const QuestionnaireModalManager = dynamic(() => import('~/features/questionnaire/client/components/QuestionnaireModalManager'), { ssr: false });
  73. const TagEditModal = dynamic(() => import('../components/PageTags/TagEditModal').then(mod => mod.TagEditModal), { ssr: false });
  74. const ConflictDiffModal = dynamic(() => import('../components/PageEditor/ConflictDiffModal').then(mod => mod.ConflictDiffModal), { ssr: false });
  75. const logger = loggerFactory('growi:pages:all');
  76. const {
  77. isPermalink: _isPermalink, isCreatablePage,
  78. } = pagePathUtils;
  79. const { removeHeadingSlash } = pathUtils;
  80. type IPageToShowRevisionWithMeta = IDataWithMeta<IPagePopulatedToShowRevision & PageDocument, IPageInfoForEntity>;
  81. type IPageToShowRevisionWithMetaSerialized = IDataWithMeta<string, string>;
  82. superjson.registerCustom<IPageToShowRevisionWithMeta, IPageToShowRevisionWithMetaSerialized>(
  83. {
  84. isApplicable: (v): v is IPageToShowRevisionWithMeta => {
  85. return v?.data != null
  86. && v?.data.toObject != null
  87. && v?.meta != null
  88. && isIPageInfoForEntity(v.meta);
  89. },
  90. serialize: (v) => {
  91. return {
  92. data: superjson.stringify(v.data.toObject()),
  93. meta: superjson.stringify(v.meta),
  94. };
  95. },
  96. deserialize: (v) => {
  97. return {
  98. data: superjson.parse(v.data),
  99. meta: v.meta != null ? superjson.parse(v.meta) : undefined,
  100. };
  101. },
  102. },
  103. 'IPageToShowRevisionWithMetaTransformer',
  104. );
  105. // GrowiContextualSubNavigation for NOT shared page
  106. type GrowiContextualSubNavigationProps = {
  107. isLinkSharingDisabled: boolean,
  108. }
  109. const GrowiContextualSubNavigation = (props: GrowiContextualSubNavigationProps): JSX.Element => {
  110. const { isLinkSharingDisabled } = props;
  111. const { data: currentPage } = useSWRxCurrentPage();
  112. return (
  113. <GrowiContextualSubNavigationSubstance currentPage={currentPage} isLinkSharingDisabled={isLinkSharingDisabled} />
  114. );
  115. };
  116. type Props = CommonProps & {
  117. pageWithMeta: IPageToShowRevisionWithMeta | null,
  118. // pageUser?: any,
  119. redirectFrom?: string;
  120. // shareLinkId?: string;
  121. isLatestRevision?: boolean,
  122. isIdenticalPathPage?: boolean,
  123. isForbidden: boolean,
  124. isNotFound: boolean,
  125. isNotCreatable: boolean,
  126. // isAbleToDeleteCompletely: boolean,
  127. templateTagData?: string[],
  128. templateBodyData?: string,
  129. isSearchServiceConfigured: boolean,
  130. isSearchServiceReachable: boolean,
  131. isSearchScopeChildrenAsDefault: boolean,
  132. isEnabledMarp: boolean,
  133. isSlackConfigured: boolean,
  134. // isMailerSetup: boolean,
  135. isAclEnabled: boolean,
  136. // hasSlackConfig: boolean,
  137. drawioUri: string | null,
  138. noCdn: string,
  139. // highlightJsStyle: string,
  140. isAllReplyShown: boolean,
  141. isContainerFluid: boolean,
  142. isUploadEnabled: boolean,
  143. isUploadAllFileAllowed: boolean,
  144. isEnabledStaleNotification: boolean,
  145. isEnabledAttachTitleHeader: boolean,
  146. // isEnabledLinebreaks: boolean,
  147. // isEnabledLinebreaksInComments: boolean,
  148. adminPreferredIndentSize: number,
  149. isIndentSizeForced: boolean,
  150. disableLinkSharing: boolean,
  151. skipSSR: boolean,
  152. ssrMaxRevisionBodyLength: number,
  153. grantData?: IPageGrantData,
  154. rendererConfig: RendererConfig,
  155. };
  156. const Page: NextPageWithLayout<Props> = (props: Props) => {
  157. // register global EventEmitter
  158. if (isClient() && window.globalEmitter == null) {
  159. window.globalEmitter = new EventEmitter();
  160. }
  161. const router = useRouter();
  162. useCurrentUser(props.currentUser ?? null);
  163. // commons
  164. useCsrfToken(props.csrfToken);
  165. useGrowiCloudUri(props.growiCloudUri);
  166. // page
  167. useIsContainerFluid(props.isContainerFluid);
  168. // useOwnerOfCurrentPage(props.pageUser != null ? JSON.parse(props.pageUser) : null);
  169. useIsForbidden(props.isForbidden);
  170. useIsNotCreatable(props.isNotCreatable);
  171. useRedirectFrom(props.redirectFrom ?? null);
  172. useIsSharedUser(false); // this page cann't be routed for '/share'
  173. useIsIdenticalPath(props.isIdenticalPathPage ?? false);
  174. useIsEnabledStaleNotification(props.isEnabledStaleNotification);
  175. useIsSearchPage(false);
  176. useIsEnabledAttachTitleHeader(props.isEnabledAttachTitleHeader);
  177. useIsSearchServiceConfigured(props.isSearchServiceConfigured);
  178. useIsSearchServiceReachable(props.isSearchServiceReachable);
  179. useIsSearchScopeChildrenAsDefault(props.isSearchScopeChildrenAsDefault);
  180. useIsSlackConfigured(props.isSlackConfigured);
  181. // useIsMailerSetup(props.isMailerSetup);
  182. useIsAclEnabled(props.isAclEnabled);
  183. // useHasSlackConfig(props.hasSlackConfig);
  184. // useNoCdn(props.noCdn);
  185. useDefaultIndentSize(props.adminPreferredIndentSize);
  186. useIsIndentSizeForced(props.isIndentSizeForced);
  187. useDisableLinkSharing(props.disableLinkSharing);
  188. useRendererConfig(props.rendererConfig);
  189. useIsEnabledMarp(props.rendererConfig.isEnabledMarp);
  190. // useRendererSettings(props.rendererSettingsStr != null ? JSON.parse(props.rendererSettingsStr) : undefined);
  191. // useGrowiRendererConfig(props.growiRendererConfigStr != null ? JSON.parse(props.growiRendererConfigStr) : undefined);
  192. useIsAllReplyShown(props.isAllReplyShown);
  193. useIsUploadAllFileAllowed(props.isUploadAllFileAllowed);
  194. useIsUploadEnabled(props.isUploadEnabled);
  195. const { pageWithMeta } = props;
  196. const pageId = pageWithMeta?.data._id;
  197. const revisionBody = pageWithMeta?.data.revision?.body;
  198. useCurrentPathname(props.currentPathname);
  199. const { data: currentPage } = useSWRxCurrentPage(pageWithMeta?.data ?? null); // store initial data
  200. const { trigger: mutateCurrentPage } = useSWRMUTxCurrentPage();
  201. const { mutate: mutateEditingMarkdown } = useEditingMarkdown();
  202. const { data: currentPageId, mutate: mutateCurrentPageId } = useCurrentPageId();
  203. const { mutate: mutateIsNotFound } = useIsNotFound();
  204. const { mutate: mutateIsLatestRevision } = useIsLatestRevision();
  205. const { data: grantData } = useSWRxIsGrantNormalized(pageId);
  206. const { mutate: mutateSelectedGrant } = useSelectedGrant();
  207. const { mutate: mutateRemoteRevisionId } = useRemoteRevisionId();
  208. const { mutate: mutateTemplateTagData } = useTemplateTagData();
  209. const { mutate: mutateTemplateBodyData } = useTemplateBodyData();
  210. useSetupGlobalSocket();
  211. useSetupGlobalSocketForPage(pageId);
  212. // Store initial data (When revisionBody is not SSR)
  213. useEffect(() => {
  214. if (!props.skipSSR) {
  215. return;
  216. }
  217. if (currentPageId != null && !props.isNotFound) {
  218. const mutatePageData = async() => {
  219. const pageData = await mutateCurrentPage();
  220. mutateEditingMarkdown(pageData?.revision?.body);
  221. };
  222. // If skipSSR is true, use the API to retrieve page data.
  223. // Because pageWIthMeta does not contain revision.body
  224. mutatePageData();
  225. }
  226. }, [currentPageId, mutateCurrentPage, mutateEditingMarkdown, props.isNotFound, props.skipSSR]);
  227. // sync grant data
  228. useEffect(() => {
  229. const grantDataToApply = props.grantData ? props.grantData : grantData?.grantData.currentPageGrant;
  230. mutateSelectedGrant(grantDataToApply);
  231. }, [grantData?.grantData.currentPageGrant, mutateSelectedGrant, props.grantData]);
  232. // sync pathname by Shallow Routing https://nextjs.org/docs/routing/shallow-routing
  233. useEffect(() => {
  234. const decodedURI = decodeURI(window.location.pathname);
  235. if (isClient() && decodedURI !== props.currentPathname) {
  236. const { search, hash } = window.location;
  237. router.replace(`${props.currentPathname}${search}${hash}`, undefined, { shallow: true });
  238. }
  239. }, [props.currentPathname, router]);
  240. // initialize mutateEditingMarkdown only once per page
  241. // need to include useCurrentPathname not useCurrentPagePath
  242. useEffect(() => {
  243. if (props.currentPathname != null) {
  244. mutateEditingMarkdown(revisionBody);
  245. }
  246. }, [mutateEditingMarkdown, revisionBody, props.currentPathname]);
  247. useEffect(() => {
  248. mutateRemoteRevisionId(pageWithMeta?.data.revision?._id);
  249. }, [mutateRemoteRevisionId, pageWithMeta?.data.revision?._id]);
  250. useEffect(() => {
  251. mutateCurrentPageId(pageId ?? null);
  252. }, [mutateCurrentPageId, pageId]);
  253. useEffect(() => {
  254. mutateIsNotFound(props.isNotFound);
  255. }, [mutateIsNotFound, props.isNotFound]);
  256. useEffect(() => {
  257. mutateIsLatestRevision(props.isLatestRevision);
  258. }, [mutateIsLatestRevision, props.isLatestRevision]);
  259. useEffect(() => {
  260. mutateTemplateTagData(props.templateTagData);
  261. }, [props.templateTagData, mutateTemplateTagData]);
  262. useEffect(() => {
  263. mutateTemplateBodyData(props.templateBodyData);
  264. }, [props.templateBodyData, mutateTemplateBodyData]);
  265. // If the data on the page changes without router.push, pageWithMeta remains old because getServerSideProps() is not executed
  266. // So preferentially take page data from useSWRxCurrentPage
  267. const pagePath = currentPage?.path ?? pageWithMeta?.data.path ?? props.currentPathname;
  268. const title = generateCustomTitleForPage(props, pagePath);
  269. return (
  270. <>
  271. <Head>
  272. <title>{title}</title>
  273. </Head>
  274. <div className="dynamic-layout-root justify-content-between">
  275. <nav className="sticky-top">
  276. <GrowiContextualSubNavigation isLinkSharingDisabled={props.disableLinkSharing} />
  277. </nav>
  278. <DisplaySwitcher
  279. pageView={(
  280. <PageView
  281. pagePath={pagePath}
  282. initialPage={pageWithMeta?.data}
  283. rendererConfig={props.rendererConfig}
  284. />
  285. )}
  286. />
  287. <PageStatusAlert />
  288. </div>
  289. </>
  290. );
  291. };
  292. const BasicLayoutWithEditor = ({ children }: { children?: ReactNode }): JSX.Element => {
  293. const editorModeClassName = useEditorModeClassName();
  294. return <BasicLayout className={editorModeClassName}>{children}</BasicLayout>;
  295. };
  296. type LayoutProps = Props & {
  297. children?: ReactNode
  298. }
  299. const Layout = ({ children, ...props }: LayoutProps): JSX.Element => {
  300. // init sidebar config with UserUISettings and sidebarConfig
  301. useInitSidebarConfig(props.sidebarConfig, props.userUISettings);
  302. return <BasicLayoutWithEditor>{children}</BasicLayoutWithEditor>;
  303. };
  304. Page.getLayout = function getLayout(page: React.ReactElement<Props>) {
  305. return (
  306. <>
  307. <GrowiPluginsActivator />
  308. <DrawioViewerScript />
  309. <Layout {...page.props}>
  310. {page}
  311. </Layout>
  312. <UnsavedAlertDialog />
  313. <DescendantsPageListModal />
  314. <DrawioModal />
  315. <HandsontableModal />
  316. <QuestionnaireModalManager />
  317. <TemplateModal />
  318. <LinkEditModal />
  319. <TagEditModal />
  320. <ConflictDiffModal />
  321. </>
  322. );
  323. };
  324. function getPageIdFromPathname(currentPathname: string): string | null {
  325. return _isPermalink(currentPathname) ? removeHeadingSlash(currentPathname) : null;
  326. }
  327. class MultiplePagesHitsError extends ExtensibleCustomError {
  328. pagePath: string;
  329. constructor(pagePath: string) {
  330. super(`MultiplePagesHitsError occured by '${pagePath}'`);
  331. this.pagePath = pagePath;
  332. }
  333. }
  334. async function injectPageData(context: GetServerSidePropsContext, props: Props): Promise<void> {
  335. const { model: mongooseModel } = await import('mongoose');
  336. const req: CrowiRequest = context.req as CrowiRequest;
  337. const { crowi } = req;
  338. const { revisionId } = req.query;
  339. const Page = crowi.model('Page') as PageModel;
  340. const PageRedirect = mongooseModel('PageRedirect') as PageRedirectModel;
  341. const { pageService, configManager, pageGrantService } = crowi;
  342. let currentPathname = props.currentPathname;
  343. const pageId = getPageIdFromPathname(currentPathname);
  344. const isPermalink = _isPermalink(currentPathname);
  345. const { user } = req;
  346. if (!isPermalink) {
  347. // check redirects
  348. const chains = await PageRedirect.retrievePageRedirectEndpoints(currentPathname);
  349. if (chains != null) {
  350. // overwrite currentPathname
  351. currentPathname = chains.end.toPath;
  352. props.currentPathname = currentPathname;
  353. // set redirectFrom
  354. props.redirectFrom = chains.start.fromPath;
  355. }
  356. // check whether the specified page path hits to multiple pages
  357. const count = await Page.countByPathAndViewer(currentPathname, user, null, true);
  358. if (count > 1) {
  359. throw new MultiplePagesHitsError(currentPathname);
  360. }
  361. }
  362. const pageWithMeta: IPageToShowRevisionWithMeta | null = await pageService.findPageAndMetaDataByViewer(pageId, currentPathname, user, true); // includeEmpty = true, isSharedPage = false
  363. const page = pageWithMeta?.data as unknown as PageDocument;
  364. // add user to seen users
  365. if (page != null && user != null) {
  366. await page.seen(user);
  367. }
  368. // populate & check if the revision is latest
  369. if (page != null) {
  370. page.initLatestRevisionField(revisionId);
  371. props.isLatestRevision = page.isLatestRevision();
  372. const ssrMaxRevisionBodyLength = configManager.getConfig('crowi', 'app:ssrMaxRevisionBodyLength');
  373. props.skipSSR = await skipSSR(page, ssrMaxRevisionBodyLength);
  374. await page.populateDataToShowRevision(props.skipSSR); // shouldExcludeBody = skipSSR
  375. }
  376. if (page == null && user != null) {
  377. const templateData = await Page.findTemplate(props.currentPathname);
  378. if (templateData != null) {
  379. props.templateTagData = templateData.templateTags as string[];
  380. props.templateBodyData = templateData.templateBody as string;
  381. }
  382. // apply parent page grant, without groups that user isn't related to
  383. const ancestor = await Page.findAncestorByPathAndViewer(currentPathname, user);
  384. if (ancestor != null) {
  385. ancestor.populate('grantedGroups.item');
  386. const userRelatedGrantedGroups = (await pageGrantService.getUserRelatedGrantedGroups(ancestor, user)).map((group) => {
  387. if (isPopulated(group.item)) {
  388. return {
  389. id: group.item._id,
  390. name: group.item.name,
  391. type: group.type,
  392. };
  393. }
  394. return null;
  395. }).filter((info): info is NonNullable<{id: string, name: string, type: GroupType}> => info != null);
  396. props.grantData = {
  397. grant: ancestor.grant,
  398. userRelatedGrantedGroups,
  399. };
  400. }
  401. }
  402. props.pageWithMeta = pageWithMeta;
  403. }
  404. async function injectRoutingInformation(context: GetServerSidePropsContext, props: Props): Promise<void> {
  405. const req: CrowiRequest = context.req as CrowiRequest;
  406. const { crowi } = req;
  407. const Page = crowi.model('Page') as PageModel;
  408. const { currentPathname } = props;
  409. const pageId = getPageIdFromPathname(currentPathname);
  410. const isPermalink = _isPermalink(currentPathname);
  411. const page = props.pageWithMeta?.data;
  412. if (props.isIdenticalPathPage) {
  413. props.isNotCreatable = true;
  414. }
  415. else if (page == null) {
  416. props.isNotFound = true;
  417. props.isNotCreatable = !isCreatablePage(currentPathname);
  418. // check the page is forbidden or just does not exist.
  419. const count = isPermalink ? await Page.count({ _id: pageId }) : await Page.count({ path: currentPathname });
  420. props.isForbidden = count > 0;
  421. }
  422. else {
  423. props.isNotFound = page.isEmpty;
  424. props.isNotCreatable = false;
  425. props.isForbidden = false;
  426. // /62a88db47fed8b2d94f30000 ==> /path/to/page
  427. if (isPermalink && page.isEmpty) {
  428. props.currentPathname = page.path;
  429. }
  430. // /path/to/page ==> /62a88db47fed8b2d94f30000
  431. if (!isPermalink && !page.isEmpty) {
  432. const isToppage = pagePathUtils.isTopPage(props.currentPathname);
  433. if (!isToppage) {
  434. props.currentPathname = `/${page._id}`;
  435. }
  436. }
  437. }
  438. }
  439. // async function injectPageUserInformation(context: GetServerSidePropsContext, props: Props): Promise<void> {
  440. // const req: CrowiRequest = context.req as CrowiRequest;
  441. // const { crowi } = req;
  442. // const UserModel = crowi.model('User');
  443. // if (isUserPage(props.currentPagePath)) {
  444. // const user = await UserModel.findUserByUsername(UserModel.getUsernameByPath(props.currentPagePath));
  445. // if (user != null) {
  446. // props.pageUser = JSON.stringify(user.toObject());
  447. // }
  448. // }
  449. // }
  450. function injectServerConfigurations(context: GetServerSidePropsContext, props: Props): void {
  451. const req: CrowiRequest = context.req as CrowiRequest;
  452. const { crowi } = req;
  453. const {
  454. searchService, configManager, aclService,
  455. } = crowi;
  456. props.isSearchServiceConfigured = searchService.isConfigured;
  457. props.isSearchServiceReachable = searchService.isReachable;
  458. props.isSearchScopeChildrenAsDefault = configManager.getConfig('crowi', 'customize:isSearchScopeChildrenAsDefault');
  459. props.isSlackConfigured = crowi.slackIntegrationService.isSlackConfigured;
  460. // props.isMailerSetup = mailService.isMailerSetup;
  461. props.isAclEnabled = aclService.isAclEnabled();
  462. // props.hasSlackConfig = slackNotificationService.hasSlackConfig();
  463. props.drawioUri = configManager.getConfig('crowi', 'app:drawioUri');
  464. props.noCdn = configManager.getConfig('crowi', 'app:noCdn');
  465. // props.highlightJsStyle = configManager.getConfig('crowi', 'customize:highlightJsStyle');
  466. props.isAllReplyShown = configManager.getConfig('crowi', 'customize:isAllReplyShown');
  467. props.isContainerFluid = configManager.getConfig('crowi', 'customize:isContainerFluid');
  468. props.isEnabledStaleNotification = configManager.getConfig('crowi', 'customize:isEnabledStaleNotification');
  469. props.disableLinkSharing = configManager.getConfig('crowi', 'security:disableLinkSharing');
  470. props.isUploadAllFileAllowed = crowi.fileUploadService.getFileUploadEnabled();
  471. props.isUploadEnabled = crowi.fileUploadService.getIsUploadable();
  472. props.adminPreferredIndentSize = configManager.getConfig('markdown', 'markdown:adminPreferredIndentSize');
  473. props.isIndentSizeForced = configManager.getConfig('markdown', 'markdown:isIndentSizeForced');
  474. props.isEnabledAttachTitleHeader = configManager.getConfig('crowi', 'customize:isEnabledAttachTitleHeader');
  475. props.rendererConfig = {
  476. isEnabledLinebreaks: configManager.getConfig('markdown', 'markdown:isEnabledLinebreaks'),
  477. isEnabledLinebreaksInComments: configManager.getConfig('markdown', 'markdown:isEnabledLinebreaksInComments'),
  478. isEnabledMarp: configManager.getConfig('crowi', 'customize:isEnabledMarp'),
  479. adminPreferredIndentSize: configManager.getConfig('markdown', 'markdown:adminPreferredIndentSize'),
  480. isIndentSizeForced: configManager.getConfig('markdown', 'markdown:isIndentSizeForced'),
  481. drawioUri: configManager.getConfig('crowi', 'app:drawioUri'),
  482. plantumlUri: configManager.getConfig('crowi', 'app:plantumlUri'),
  483. // XSS Options
  484. isEnabledXssPrevention: configManager.getConfig('markdown', 'markdown:rehypeSanitize:isEnabledPrevention'),
  485. xssOption: configManager.getConfig('markdown', 'markdown:rehypeSanitize:option'),
  486. attrWhitelist: JSON.parse(crowi.configManager.getConfig('markdown', 'markdown:rehypeSanitize:attributes')),
  487. tagWhitelist: crowi.configManager.getConfig('markdown', 'markdown:rehypeSanitize:tagNames'),
  488. highlightJsStyleBorder: crowi.configManager.getConfig('crowi', 'customize:highlightJsStyleBorder'),
  489. };
  490. props.ssrMaxRevisionBodyLength = configManager.getConfig('crowi', 'app:ssrMaxRevisionBodyLength');
  491. }
  492. /**
  493. * for Server Side Translations
  494. * @param context
  495. * @param props
  496. * @param namespacesRequired
  497. */
  498. async function injectNextI18NextConfigurations(context: GetServerSidePropsContext, props: Props, namespacesRequired?: string[] | undefined): Promise<void> {
  499. const nextI18NextConfig = await getNextI18NextConfig(serverSideTranslations, context, namespacesRequired);
  500. props._nextI18Next = nextI18NextConfig._nextI18Next;
  501. }
  502. const getAction = (props: Props): SupportedActionType => {
  503. if (props.isNotCreatable) {
  504. return SupportedAction.ACTION_PAGE_NOT_CREATABLE;
  505. }
  506. if (props.isForbidden) {
  507. return SupportedAction.ACTION_PAGE_FORBIDDEN;
  508. }
  509. if (props.isNotFound) {
  510. return SupportedAction.ACTION_PAGE_NOT_FOUND;
  511. }
  512. if (pagePathUtils.isUsersHomepage(props.pageWithMeta?.data.path ?? '')) {
  513. return SupportedAction.ACTION_PAGE_USER_HOME_VIEW;
  514. }
  515. return SupportedAction.ACTION_PAGE_VIEW;
  516. };
  517. export const getServerSideProps: GetServerSideProps = async(context: GetServerSidePropsContext) => {
  518. const req = context.req as CrowiRequest;
  519. const { user } = req;
  520. const result = await getServerSideCommonProps(context);
  521. // check for presence
  522. // see: https://github.com/vercel/next.js/issues/19271#issuecomment-730006862
  523. if (!('props' in result)) {
  524. throw new Error('invalid getSSP result');
  525. }
  526. const props: Props = result.props as Props;
  527. if (props.redirectDestination != null) {
  528. return {
  529. redirect: {
  530. permanent: false,
  531. destination: props.redirectDestination,
  532. },
  533. };
  534. }
  535. if (user != null) {
  536. props.currentUser = user.toObject();
  537. }
  538. try {
  539. await injectPageData(context, props);
  540. }
  541. catch (err) {
  542. if (err instanceof MultiplePagesHitsError) {
  543. props.isIdenticalPathPage = true;
  544. }
  545. else {
  546. throw err;
  547. }
  548. }
  549. await injectRoutingInformation(context, props);
  550. injectServerConfigurations(context, props);
  551. await injectNextI18NextConfigurations(context, props, ['translation']);
  552. addActivity(context, getAction(props));
  553. return {
  554. props,
  555. };
  556. };
  557. export default Page;